import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '日期时间选择',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        splashColor: Colors.transparent,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 当前时间
  DateTime dateTime = DateTime.now();

  // 定义时间
  TimeOfDay timeOfDay = TimeOfDay(hour: 9, minute: 34);

  // 日期选择弹框
  _selectDate() async {
    final selectedDate = await showDatePicker(
      context: context,
      initialDate: dateTime,
      // 开始、结束日期限制
      firstDate: DateTime(1992),
      lastDate: DateTime(2025),
    );

    if (selectedDate != null) {
      setState(() {
        dateTime = selectedDate;
      });
    }
  }

  // 时间选择
  _selectTime() async {
    final selectedTime =
        await showTimePicker(context: context, initialTime: timeOfDay);
    if (selectedTime != null) {
      setState(() {
        timeOfDay = selectedTime;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('日期时间选择'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
              onTap: _selectDate,
              child: Text(DateFormat.yMMMd().format(dateTime)),
            ),
            SizedBox(
              height: 18.0,
            ),
            InkWell(
              onTap: _selectTime,
              child: Text(timeOfDay.format(context)),
            ),
          ],
        ),
      ),
    );
  }
}
